#!/bin/sh
# Job yaml can send below ENVIRONMENT VARIABLES to me
# - runmins
# - warehouses
# - loadWorkers
# - terminals
# - _mysql_port
# - _root_pwd
# - _data_dir
# - _mysql_db
# END ENVIRONMENT VARIABLES


runMins=${runmins:-10}
warehouses=${warehouses:-1000}
loadworkers=${loadWorkers:-50}
terminals=${terminals:-150}
_mysql_port=${_mysql_port:-3306}
_root_pwd=${_root_pwd:-123456}
_data_dir=${_data_dir:-/data}
_mysql_db=${_mysql_db:-tpcc}


. $LKP_SRC/lib/common.sh
. $LKP_SRC/lib/upload.sh


program_root="${LKP_SRC}/programs/mysql_performance"

BENCHMARK_ROOT=/home/mysql_test
mkdir -p ${BENCHMARK_ROOT}
script_path=$(cd $(dirname $0)||exit 1;pwd)
benchmark_pkg_url="https://api.compass-ci.openeuler.org:20009/os/install/performance_tools/benchmarksql5.0-for-mysql.tar.gz"
pkg_name=$(basename $benchmark_pkg_url)
test_path="${BENCHMARK_ROOT}/${pkg_name%.tar.gz}/run"


log_dir="${TMP_RESULT_ROOT}/logs"
[ -e ${log_dir} ] && rm -rf ${log_dir}
mkdir -p ${log_dir}
result_file="${TMP_RESULT_ROOT}/mysql_performance"


benchmark_install()
{
	yum install -y java wget tar mysql
        if [ $? -ne 0 ];then
           echo "java wget tar mysql depends install failed!!!" >&2 && exit 1
        fi
        cd "$BENCHMARK_ROOT"
        wget "$benchmark_pkg_url"
        tar -xzf "$pkg_name"      
        if [ -e "${test_path}" ];then
           echo "benchmark install success"
        else
           echo "benchmark install failed!!!" >&2 && exit 1
        fi

}

exec_test()
{
        echo 3 > /proc/sys/vm/drop_caches

        mysql -uroot -P"${_mysql_port}" -h server -p"${_root_pwd}" -e "create database ${_mysql_db}"
        # prepare data
        ./runDatabaseBuild.sh props.conf 2>&1|tee -a "${log_dir}/database_build.log" 
        sleep 30
        # exec test
        ./runBenchmark.sh props.conf 2>&1|tee -a "${log_dir}/test.log"
}

test_mysql()
{
        cd ${test_path}
        chmod 755 ./*
        \cp "${program_root}/conf/props.conf" props.conf
        sed -i "s#{mysql_port}#${_mysql_port}#" props.conf
        sed -i "s#{mysql_db}#${_mysql_db}#" props.conf
        sed -i "s#{root_pwd}#${_root_pwd}#" props.conf
        sed -i "s#{data_dir}#${_data_dir}#g" props.conf
        sed -i "s#{warehouses}#${warehouses}#" props.conf
        sed -i "s#{loadworkers}#${loadworkers}#" props.conf
        sed -i "s#{terminals}#${terminals}#" props.conf
        sed -i "s#{runmins}#${runmins}#" props.conf
        
        exec_test
                
}


deal_result()
{
        result=$(grep 'Measured tpmC (NewOrders)' "${log_dir}/test.log"|tail -n 1|awk -F '[= ]+' '{print $NF}')
        echo "tpcc ${result}" > ${result_file} 
}

main()
{
        benchmark_install
        test_mysql
        deal_result
}

main

upload_files -t results ${log_dir}/*
